package com.newfiber.common.core.web.support;

import java.lang.reflect.Field;
import java.sql.Connection;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

/**
 * @author : X.K
 * @since : 2023/4/18 下午1:48
 */
@Component
@Intercepts(@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}))
public class QueryDeletedInterceptor implements Interceptor {

	/**
	 * 用法 ： queryWrapper = new QueryWrapper<T>().last(QueryDeletedInterceptor.QUERY_DELETED_DATA);
	 */


	public static final String QUERY_DELETED_DATA = "query_deleted_data = true";

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
		BoundSql boundSql = statementHandler.getBoundSql();
		String sql = boundSql.getSql();

		if (sql.contains(QUERY_DELETED_DATA)) {
			sql = sql.replaceAll("del_flag='0'", " 1 = 1 ").replace(QUERY_DELETED_DATA, "");
		}else{
			return invocation.proceed();
		}

		//通过反射修改sql
		Field field = boundSql.getClass().getDeclaredField("sql");
		field.setAccessible(true);
		field.set(boundSql, sql);
		return invocation.proceed();
	}
}
